package MawsonClient.GUI;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;

/**
 * User: Ryan Green
 * Date: 12/1/11
 * Time: 9:06 PM
 * Copyright - University of South Australia
 */
public class PerAggPanel extends JPanel {

	MawsonFrame frame;

	PerAggPanel(MawsonFrame frame){
		super();

		this.frame = frame;

		//do per aggregate panel
		this.setLayout(new CardLayout());
		int counter = 0;

		HashSet<String> set = new HashSet<String>();
		for (String str : frame.aggMap.values()) {
			set.add(str);
		}
		String[] vals = set.toArray(new String[0]);

		for (ArrayList<RequestedDataElement> list : frame.perAggElements) {
			JPanel centrePanel = new JPanel(new GridLayout(0, 2, 5, 5));
			centrePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Per Aggregate Data"));
			centrePanel.add(new JLabel("Specimen ID:"));
			centrePanel.add(new JLabel(vals[counter]));
			for (RequestedDataElement element : list) {
				centrePanel.add(new JLabel(element.label));
				centrePanel.add(element.comp);
				element.setVal(vals[counter]);
			}
			JPanel holdingPanel = new JPanel(new BorderLayout());
			holdingPanel.add(new JLabel(" "), BorderLayout.CENTER);
			holdingPanel.add(centrePanel, BorderLayout.NORTH);
			JCheckBox skipCheckBox = new JCheckBox("Ignore this sample");
			skipCheckBox.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent actionEvent) {
					JCheckBox skipCheckBox = (JCheckBox)actionEvent.getSource();
					Component c[] = skipCheckBox.getParent().getComponents();
					JPanel currentPanel = (JPanel)c[1];
					c = currentPanel.getComponents();
					for (int i = 0; i < c.length; i++){
						if (!(c[i] instanceof JCheckBox)) c[i].setEnabled(!skipCheckBox.isSelected());
					}

					JLabel id = (JLabel)currentPanel.getComponent(1);
					SkipValueChanged(skipCheckBox.isSelected(), id.getText());
				}
			});
			holdingPanel.add(skipCheckBox, BorderLayout.SOUTH);
			this.add(holdingPanel, vals[counter]);
			counter++;
		}
	}

	private void SkipValueChanged(boolean selected, String text) {
		if (selected)frame.skipList.add(text);
		else frame.skipList.remove(text);
	}
}
